from datetime import datetime, timedelta
import hashlib
import os
import sys
from time import sleep
import requests
import schedule
from libs.TSData import TSData
import time
import board
import busio
from adafruit_ads1x15.ads1115 import ADS1115
from adafruit_ads1x15.analog_in import AnalogIn


server_ip = '127.0.0.1'
server_port = '8888'
client_id = 'your_client_id'  # 客户端 ID

with open('status/client_id', 'r') as file:
    client_id = file.read().strip()
with open('status/server_ip', 'r') as file:
    server_ip = file.read().strip()
with open('status/server_port', 'r') as file:
    server_port = file.read().strip()

server_url = f'http://{server_ip}:{server_port}'
url_check = server_url + '/api/check_elec_upload' # 检测地址
url_upload = server_url + '/api/upload_elec_data'  # 服务器地址


# 计算文件的 MD5 值
def calculate_md5(file_path):
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


def upload_elec_file(data_date: datetime, check: bool = True):
    file_path = f'elec_data/{data_date.strftime("%Y-%m-%d")}_second.bin'
    if not os.path.exists(file_path):
        print(f"File {file_path} does not exist.")
        return
    # 计算文件的 MD5 值
    file_hash = calculate_md5(file_path)

    # 检查文件是否已上传
    response_check = requests.post(url_check, json={
        'client_id': client_id, 
        'data_date': data_date.strftime('%Y-%m-%d'), 
        'file_hash': file_hash
    }, headers={
        "Content-Type": "application/json" 
    })

    if response_check.status_code == 200 and response_check.json()['status'] == 'ok':
        print("File already uploaded, skipping upload.")
    else:
        # 如果文件没有上传过，执行上传
        with open(file_path, 'rb') as file:
            files = {'file': (file_path, file)}
            data = {'client_id': client_id, 'data_date': data_date.strftime('%Y-%m-%d')}  # 添加 MD5 参数
            response_upload = requests.post(url_upload, files=files, data=data)
            print(response_upload.json())
            if response_upload.status_code == 200:
                if response_upload.json()['status'] == 'ok':
                    print("File uploaded successfully.")
                else:
                    print(response_upload.json()['msg'])
            else:
                print("Failed to upload file.")


def upload_yesterday_elec_file():
    yesterday = datetime.now() - timedelta(1)  # 获取昨天的日期
    upload_elec_file(yesterday)

def upload_today_elec_file():
    today = datetime.now()  # 获取今天的日期
    upload_elec_file(today, False)


def read_voltage():# 初始化 I2C 总线
    i2c = busio.I2C(board.SCL, board.SDA)

    # 创建 ADS1115 对象
    ads = ADS1115(i2c)

    # 创建模拟输入通道
    chan = AnalogIn(ads, 0)  # 使用通道 0

    voltage_value = chan.voltage * 5 
    print("ADC Reading: ", chan.value)
    print(f"Voltage: {voltage_value:.3f} V")
    return int(voltage_value * 1000) + 32767  # 将电压值转换为整数, 单位为mV，并且做偏移，以便允许负值


def record_voltage():
    voltage_value = read_voltage()
    TSData.write_now(voltage_value, 'elec_data')


schedule.every(1).hour.do(upload_yesterday_elec_file) # 每小时执行一次上传昨天的数据
schedule.every(1).second.do(record_voltage) # 每秒记录一次电压值

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1].lower() == 'today':
        upload_today_elec_file()
    else:
        # 否则默认执行下面的命令：
        upload_yesterday_elec_file() # 首先立即上传昨天的数据
        while True:
            schedule.run_pending()
            sleep(1)



